package com.landray.kmss.yggs.todonotify;

import com.alibaba.fastjson.JSON;
import com.koron.bean.base.Response;
import com.koron.bean.query.Page;
import com.koron.common.core.business.workflow.bean.param.ListParam;
import com.koron.common.core.business.workflow.bean.result.FlowList;
import com.koron.common.core.business.workflow.bean.result.TaskStatistics;
import com.koron.common.core.business.workflow.service.SysWorkflowService;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.StringUtils;
import com.koron.order.workbench.todoCenter.controller.TodoController;
import com.landray.kmss.yggs.todonotify.webservice.Exception_Exception;
import com.landray.kmss.yggs.todonotify.webservice.IYggsTodonotifyTodoWebServiceService;
import com.landray.kmss.yggs.todonotify.webservice.YggsTodonotifyTodoParamterForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @ClassName EamWebServiceClient
 * @description
 * @Author zhouj
 * @Date 2022/2/23 14:19
 */
@Slf4j
@Component
@Api(tags = "待办推送oa()")
@RequestMapping("/todo/")
@RestController
@RefreshScope
public class EamWebServiceClient {

    @Autowired
    SysWorkflowService workflowService;

    @Autowired
    IYggsTodonotifyTodoWebServiceService webServiceService;

    @Value("${oa.todo.identifier}")
    private String identifier;

    @Autowired
    TodoController todoController;

    /*
     * 功能描述 代办数量的变化,发送给oa
     * @author zhouj
     * @date 2022/2/23 14:24
     * @param [fdUsername 用户账号, fdTodos 用户代办数量]
     * @return java.lang.String
     */
    @ApiOperation(value = "推送代办数量到oa ")
    @GetMapping("/sendToOa")
    public Response<String> sendToOa(String fdUsername, String count) {

        try {
            // 请在此处添加业务代码
            //根据账号查询某个人的待办数量

            //1.1 判断是否需要代办数量发送给oa
            WebServiceConfig cfg = WebServiceConfig.getInstance();
            if (!cfg.getSend()) {
                log.info("不需要oa待办推送");
                return Response.ok();
            }

            //1.2 查询单个人员的代办数量
            if (StringUtils.isEmpty(count)) {
                ListParam listParam = new ListParam();
                if (!StringUtils.isEmpty(fdUsername)) {
                    listParam.setOperator(fdUsername);
                }
                Page<FlowList> flowListPage = workflowService.listBill(listParam);
                count = String.valueOf(flowListPage.getTotal());
            }

            //1.3 准备推送oa待办
            YggsTodonotifyTodoParamterForm form = new YggsTodonotifyTodoParamterForm();
            form.setFdUsername(fdUsername);
            form.setFdTodos(String.valueOf(count));
            form.setFdIdentifier(identifier);
            String info = webServiceService.save(form);
            log.info("推送oa待办返回:{}", info);
            return Response.ok(info);
        } catch (Exception | Exception_Exception e) {
            log.error(e.getMessage(), e);
            return Response.ok(e.getMessage());
        }
    }

    /*
     * 功能描述 工作流引起代办数量的变化,发送给oa
     * @author zhouj
     * @date 2022/2/23 14:24
     * @param [fdUsername 用户账号, fdTodos 用户代办数量]
     * @return java.lang.String
     */
    @ApiOperation(value = "推送代办数量到oa ")
    @GetMapping("/sendUsersToOa")
    public Response<String> sendUsersToOa(@RequestParam(value = "fdUsernameList", required = false) List<String> fdUsernameList) {

        try {
            // 1.1 判空传入的人员账号列表
            if (CollectionUtils.isEmpty(fdUsernameList)) {
                return Response.ok(null);
            }
            log.debug("更新代办数量人员列表:{}", JSON.toJSONString(fdUsernameList));

            // 1.2 工作流提供按照多个账号查询待办列表
            List<TaskStatistics> taskStatistics = workflowService.listUserTaskStatistics(null, null, fdUsernameList);
            if (taskStatistics == null) {
                return Response.ok(null);
            }

            Map<String, String> userCount = taskStatistics.stream().collect(Collectors.toMap(TaskStatistics::getAccount, TaskStatistics::getCount, (o1, o2) -> o1));
            // 1.3 webService只提供单个人员推送
            for (String s : fdUsernameList) {
                sendToOa(s, userCount.getOrDefault(s, "0"));
            }

            log.debug("更新代办数量人员列表:{},目标水司:{}", JSON.toJSONString(fdUsernameList), ThreadLocalContext.get().getCurrDs());

            // 1.4 webSocket推送代办数量至eam前端展示
            todoController.pushUndoGroupSimple(fdUsernameList, ThreadLocalContext.get().getCurrDs());

            return Response.ok(null);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.ok(e.getMessage());
        }
    }

    /*
     * 功能描述 获取所有人的待办
     * @author zhouj
     * @date 2022/2/23 14:24
     * @param
     * @return java.lang.String
     */
    @ApiOperation(value = "获取所有人的待办数量 ")
    @GetMapping("/getAllUserTodos")
    public OaResponse getAllUserTodos(@RequestParam(value = "accountList", required = false) List<String> accountList) {

        try {
            // 请在此处添加业务代码
            //查询全部人的待办数量
            List<TaskStatistics> taskStatistics = workflowService.listUserTaskStatistics(null, null, accountList);

            return OaResponse.ok(taskStatistics, (long) taskStatistics.size(), identifier);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return OaResponse.fail();
        }
    }

}
